// 《围棋》作者版权所有。版权所有。
// 此源代码的使用受BSD样式
// 许可证的约束，该许可证可以在许可证文件中找到。

package trace

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"math/rand"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	_ "unsafe"
)

func goCmd() string {
	var exeSuffix string
	if runtime.GOOS == "windows" {
		exeSuffix = ".exe"
	}
	path := filepath.Join(runtime.GOROOT(), "bin", "go"+exeSuffix)
	if _, err := os.Stat(path); err == nil {
		return path
	}
	return "go"
}

// 事件描述跟踪中的一个事件。
type Event struct {
	Off   int       // 输入文件中的偏移量（用于调试和错误报告）
	Type  byte      // Ev*
	seq   int64     // 序列号
	Ts    int64     // 事件发生的纳秒时间戳
	P     int       // P（可以是TimerP、NetpollP、SyscallP中的一个）
	G     uint64    // G事件发生在其上
	StkID uint64    // 唯一堆栈ID 
	Stk   []*Frame  // 堆栈跟踪（可以为空）
	Args  [3]uint64 // 特定于事件类型的参数
	SArgs []string  // 特定于事件类型的字符串参数
	// 链接事件（可以为零），取决于事件类型：
	// 对于GCStart:GCStop 
	// 对于GCSTWStart:GCSTWDone 
	// 对于GCSweepStart:GCSweepDone 
	// 对于GoCreate:GoStart/GoStartLabel:关联GoEnd，GoBlock或其他阻塞事件
	// 对于GoSched/GoPreempt:下一个GoStart 
	// 对于GoBlock或其他阻塞事件：解除阻塞事件
	// 对于GoUnblock:关联的GoStart 
	// 对于阻塞GoSysCall:关联的GoSysExit 
	// 对于GCMarkAssistStart:关联的GCMARKASSISTSDONE 
	// 对于UserTaskCreate:UserTaskEnd 
	// 对于UserRegion:如果是起始区域，则对应的UserRegion end事件
	Link *Event
}

// 帧是堆栈跟踪中的帧。
type Frame struct {
	PC   uint64
	Fn   string
	File string
	Line int
}

const (
	// 特殊P标识符：
	FakeP    = 1000000 + iota
	TimerP   // 描述计时器解锁
	NetpollP // 描述网络解锁
	SyscallP // 描述系统调用返回
	GCP      // 描述GC状态
)

// 解析结果是解析的结果。
type ParseResult struct {
	// 事件是跟踪中事件的排序列表。
	Events []*Event
	// Stacks是由跟踪中的堆栈ID设置的堆栈跟踪。
	Stacks map[uint64][]*Frame
}

// 解析、后处理和验证跟踪。
func Parse(r io.Reader, bin string) (ParseResult, error) {
	ver, res, err := parse(r, bin)
	if err != nil {
		return ParseResult{}, err
	}
	if ver < 1007 && bin == "" {
		return ParseResult{}, fmt.Errorf("for traces produced by go 1.6 or below, the binary argument must be provided")
	}
	return res, nil
}

// 解析、后处理和验证跟踪。它返回
// 跟踪版本和事件列表。
func parse(r io.Reader, bin string) (int, ParseResult, error) {
	ver, rawEvents, strings, err := readTrace(r)
	if err != nil {
		return 0, ParseResult{}, err
	}
	events, stacks, err := parseEvents(ver, rawEvents, strings)
	if err != nil {
		return 0, ParseResult{}, err
	}
	events = removeFutile(events)
	err = postProcessTrace(ver, events)
	if err != nil {
		return 0, ParseResult{}, err
	}
	// 附加堆栈跟踪。
	for _, ev := range events {
		if ev.StkID != 0 {
			ev.Stk = stacks[ev.StkID]
		}
	}
	if ver < 1007 && bin != "" {
		if err := symbolize(events, bin); err != nil {
			return 0, ParseResult{}, err
		}
	}
	return ver, ParseResult{Events: events, Stacks: stacks}, nil
}

// rawEvent是解析过程中使用的帮助器类型。
type rawEvent struct {
	off   int
	typ   byte
	args  []uint64
	sargs []string
}

// readTrace进行有线格式解析和验证。
// 它不关心特定的事件类型和参数含义。
func readTrace(r io.Reader) (ver int, events []rawEvent, strings map[uint64]string, err error) {
	// 读取并验证跟踪头。
	var buf [16]byte
	off, err := io.ReadFull(r, buf[:])
	if err != nil {
		err = fmt.Errorf("failed to read header: read %v, err %v", off, err)
		return
	}
	ver, err = parseHeader(buf[:])
	if err != nil {
		return
	}
	switch ver {
	case 1005, 1007, 1008, 1009, 1010, 1011:
		// 注意：添加新版本时，使用mkcanted.bash将旧版本中的罐装跟踪添加到测试套件中。
		break
	default:
		err = fmt.Errorf("unsupported trace file version %v.%v (update Go toolchain) %v", ver/1000, ver%1000, ver)
		return
	}

	// 读取事件。
	strings = make(map[uint64]string)
	for {
		// 读取事件类型和参数数（1字节）。
		off0 := off
		var n int
		n, err = r.Read(buf[:1])
		if err == io.EOF {
			err = nil
			break
		}
		if err != nil || n != 1 {
			err = fmt.Errorf("failed to read trace at offset 0x%x: n=%v err=%v", off0, n, err)
			return
		}
		off += n
		typ := buf[0] << 2 >> 2
		narg := buf[0]>>6 + 1
		inlineArgs := byte(4)
		if ver < 1007 {
			narg++
			inlineArgs++
		}
		if typ == EvNone || typ >= EvCount || EventDescriptions[typ].minVersion > ver {
			err = fmt.Errorf("unknown event type %v at offset 0x%x", typ, off0)
			return
		}
		if typ == EvString {
			// 字符串字典条目[ID，长度，字符串]。
			var id uint64
			id, off, err = readVal(r, off)
			if err != nil {
				return
			}
			if id == 0 {
				err = fmt.Errorf("string at offset %d has invalid id 0", off)
				return
			}
			if strings[id] != "" {
				err = fmt.Errorf("string at offset %d has duplicate id %v", off, id)
				return
			}
			var ln uint64
			ln, off, err = readVal(r, off)
			if err != nil {
				return
			}
			if ln == 0 {
				err = fmt.Errorf("string at offset %d has invalid length 0", off)
				return
			}
			if ln > 1e6 {
				err = fmt.Errorf("string at offset %d has too large length %v", off, ln)
				return
			}
			buf := make([]byte, ln)
			var n int
			n, err = io.ReadFull(r, buf)
			if err != nil {
				err = fmt.Errorf("failed to read trace at offset %d: read %v, want %v, error %v", off, n, ln, err)
				return
			}
			off += n
			strings[id] = string(buf)
			continue
		}
		ev := rawEvent{typ: typ, off: off0}
		if narg < inlineArgs {
			for i := 0; i < int(narg); i++ {
				var v uint64
				v, off, err = readVal(r, off)
				if err != nil {
					err = fmt.Errorf("failed to read event %v argument at offset %v (%v)", typ, off, err)
					return
				}
				ev.args = append(ev.args, v)
			}
		} else {
			// 比inlineArgs args args多，第一个值是事件的长度（以字节为单位）。
			var v uint64
			v, off, err = readVal(r, off)
			if err != nil {
				err = fmt.Errorf("failed to read event %v argument at offset %v (%v)", typ, off, err)
				return
			}
			evLen := v
			off1 := off
			for evLen > uint64(off-off1) {
				v, off, err = readVal(r, off)
				if err != nil {
					err = fmt.Errorf("failed to read event %v argument at offset %v (%v)", typ, off, err)
					return
				}
				ev.args = append(ev.args, v)
			}
			if evLen != uint64(off-off1) {
				err = fmt.Errorf("event has wrong length at offset 0x%x: want %v, got %v", off0, evLen, off-off1)
				return
			}
		}
		switch ev.typ {
		case EvUserLog: // EvUserLog记录后跟一个长度为ev.args[len（ev.args）-1]
			var s string
			s, off, err = readStr(r, off)
			ev.sargs = append(ev.sargs, s)
		}
		events = append(events, ev)
	}
	return
}

func readStr(r io.Reader, off0 int) (s string, off int, err error) {
	var sz uint64
	sz, off, err = readVal(r, off0)
	if err != nil || sz == 0 {
		return "", off, err
	}
	if sz > 1e6 {
		return "", off, fmt.Errorf("string at offset %d is too large (len=%d)", off, sz)
	}
	buf := make([]byte, sz)
	n, err := io.ReadFull(r, buf)
	if err != nil || sz != uint64(n) {
		return "", off + n, fmt.Errorf("failed to read trace at offset %d: read %v, want %v, error %v", off, n, sz, err)
	}
	return string(buf), off + n, nil
}

// parseHeader解析形式为“go 1.7 trace\x00\x00\x00\x00\x00”的跟踪头
// 并将解析后的版本返回为1007。
func parseHeader(buf []byte) (int, error) {
	if len(buf) != 16 {
		return 0, fmt.Errorf("bad header length")
	}
	if buf[0] != 'g' || buf[1] != 'o' || buf[2] != ' ' ||
		buf[3] < '1' || buf[3] > '9' ||
		buf[4] != '.' ||
		buf[5] < '1' || buf[5] > '9' {
		return 0, fmt.Errorf("not a trace file")
	}
	ver := int(buf[5] - '0')
	i := 0
	for ; buf[6+i] >= '0' && buf[6+i] <= '9' && i < 2; i++ {
		ver = ver*10 + int(buf[6+i]-'0')
	}
	ver += int(buf[3]-'0') * 1000
	if !bytes.Equal(buf[6+i:], []byte(" trace\x00\x00\x00\x00")[:10-i]) {
		return 0, fmt.Errorf("not a trace file")
	}
	return ver, nil
}

// 解析事件将原始事件转换为事件。
// 它会分析和验证每个事件类型的参数。
func parseEvents(ver int, rawEvents []rawEvent, strings map[uint64]string) (events []*Event, stacks map[uint64][]*Frame, err error) {
	var ticksPerSec, lastSeq, lastTs int64
	var lastG uint64
	var lastP int
	timerGoids := make(map[uint64]bool)
	lastGs := make(map[int]uint64) // 在P 
	stacks = make(map[uint64][]*Frame)
	batches := make(map[int][]*Event) // 上运行的最后一个goroutine由P 
	for _, raw := range rawEvents {
		desc := EventDescriptions[raw.typ]
		if desc.Name == "" {
			err = fmt.Errorf("missing description for event type %v", raw.typ)
			return
		}
		narg := argNum(raw, ver)
		if len(raw.args) != narg {
			err = fmt.Errorf("%v has wrong number of arguments at offset 0x%x: want %v, got %v",
				desc.Name, raw.off, narg, len(raw.args))
			return
		}
		switch raw.typ {
		case EvBatch:
			lastGs[lastP] = lastG
			lastP = int(raw.args[0])
			lastG = lastGs[lastP]
			if ver < 1007 {
				lastSeq = int64(raw.args[1])
				lastTs = int64(raw.args[2])
			} else {
				lastTs = int64(raw.args[1])
			}
		case EvFrequency:
			ticksPerSec = int64(raw.args[0])
			if ticksPerSec <= 0 {
				// 最有可能的原因是不同CPU上的勾号偏差。
				// 例如，solaris/amd64在不同的CPU上似乎有很大的不同。
				err = ErrTimeOrder
				return
			}
		case EvTimerGoroutine:
			timerGoids[raw.args[0]] = true
		case EvStack:
			if len(raw.args) < 2 {
				err = fmt.Errorf("EvStack has wrong number of arguments at offset 0x%x: want at least 2, got %v",
					raw.off, len(raw.args))
				return
			}
			size := raw.args[1]
			if size > 1000 {
				err = fmt.Errorf("EvStack has bad number of frames at offset 0x%x: %v",
					raw.off, size)
				return
			}
			want := 2 + 4*size
			if ver < 1007 {
				want = 2 + size
			}
			if uint64(len(raw.args)) != want {
				err = fmt.Errorf("EvStack has wrong number of arguments at offset 0x%x: want %v, got %v",
					raw.off, want, len(raw.args))
				return
			}
			id := raw.args[0]
			if id != 0 && size > 0 {
				stk := make([]*Frame, size)
				for i := 0; i < int(size); i++ {
					if ver < 1007 {
						stk[i] = &Frame{PC: raw.args[2+i]}
					} else {
						pc := raw.args[2+i*4+0]
						fn := raw.args[2+i*4+1]
						file := raw.args[2+i*4+2]
						line := raw.args[2+i*4+3]
						stk[i] = &Frame{PC: pc, Fn: strings[fn], File: strings[file], Line: int(line)}
					}
				}
				stacks[id] = stk
			}
		default:
			e := &Event{Off: raw.off, Type: raw.typ, P: lastP, G: lastG}
			var argOffset int
			if ver < 1007 {
				e.seq = lastSeq + int64(raw.args[0])
				e.Ts = lastTs + int64(raw.args[1])
				lastSeq = e.seq
				argOffset = 2
			} else {
				e.Ts = lastTs + int64(raw.args[0])
				argOffset = 1
			}
			lastTs = e.Ts
			for i := argOffset; i < narg; i++ {
				if i == narg-1 && desc.Stack {
					e.StkID = raw.args[i]
				} else {
					e.Args[i-argOffset] = raw.args[i]
				}
			}
			switch raw.typ {
			case EvGoStart, EvGoStartLocal, EvGoStartLabel:
				lastG = e.Args[0]
				e.G = lastG
				if raw.typ == EvGoStartLabel {
					e.SArgs = []string{strings[e.Args[2]]}
				}
			case EvGCSTWStart:
				e.G = 0
				switch e.Args[0] {
				case 0:
					e.SArgs = []string{"mark termination"}
				case 1:
					e.SArgs = []string{"sweep termination"}
				default:
					err = fmt.Errorf("unknown STW kind %d", e.Args[0])
					return
				}
			case EvGCStart, EvGCDone, EvGCSTWDone:
				e.G = 0
			case EvGoEnd, EvGoStop, EvGoSched, EvGoPreempt,
				EvGoSleep, EvGoBlock, EvGoBlockSend, EvGoBlockRecv,
				EvGoBlockSelect, EvGoBlockSync, EvGoBlockCond, EvGoBlockNet,
				EvGoSysBlock, EvGoBlockGC:
				lastG = 0
			case EvGoSysExit, EvGoWaiting, EvGoInSyscall:
				e.G = e.Args[0]
			case EvUserTaskCreate:
				// e.Args 0:taskID，1:parentID，2:nameID 
				e.SArgs = []string{strings[e.Args[2]]}
			case EvUserRegion:
				// e.Args 0:taskID，1:mode，2:nameID 
				e.SArgs = []string{strings[e.Args[2]]}
			case EvUserLog:
				// e.Args 0:taskID，1:keyID，2:stackID 
				e.SArgs = []string{strings[e.Args[1]], raw.sargs[0]}
			}
			batches[lastP] = append(batches[lastP], e)
		}
	}
	if len(batches) == 0 {
		err = fmt.Errorf("trace is empty")
		return
	}
	if ticksPerSec == 0 {
		err = fmt.Errorf("no EvFrequency event")
		return
	}
	if BreakTimestampsForTesting {
		var batchArr [][]*Event
		for _, batch := range batches {
			batchArr = append(batchArr, batch)
		}
		for i := 0; i < 5; i++ {
			batch := batchArr[rand.Intn(len(batchArr))]
			batch[rand.Intn(len(batch))].Ts += int64(rand.Intn(2000) - 1000)
		}
	}
	if ver < 1007 {
		events, err = order1005(batches)
	} else {
		events, err = order1007(batches)
	}
	if err != nil {
		return
	}

	// 将cpu时钟转换为实时。
	minTs := events[0].Ts
	// 使用浮点避免整数溢出。
	freq := 1e9 / float64(ticksPerSec)
	for _, ev := range events {
		ev.Ts = int64(float64(ev.Ts-minTs) * freq)
		// 移动计时器和系统调用以分离假Ps。
		if timerGoids[ev.G] && ev.Type == EvGoUnblock {
			ev.P = TimerP
		}
		if ev.Type == EvGoSysExit {
			ev.P = SyscallP
		}
	}

	return
}

// removeFutile删除无效唤醒的所有组成部分（阻塞、取消阻塞、启动）。
// 例如，一个goroutine在互斥对象上被解除阻止，但另一个goroutine提前获得了
// 并在调度第一个goroutine之前获得了互斥对象，因此第一个goroutine必须再次阻止。这种唤醒发生在缓冲的
// 通道和sync.Mutex上，但最终用户通常对此不感兴趣。
func removeFutile(events []*Event) []*Event {
	// 两个非常重要的方面：
	// 1。一个goroutine可以在无效的唤醒过程中被抢占并迁移到另一个P.
	// 我们想删除所有这些。
	// 2。追踪可以在无效唤醒的中间开始。
	// 也就是说，我们可以看到一个无效的唤醒事件，而之前没有实际的唤醒。
	// 后处理跟踪在我们之后运行，并确保跟踪保持一致状态。

	// 第一阶段：确定无效的唤醒序列。
	type G struct {
		futile bool
		wakeup []*Event // 唤醒序列（移除对象）
	}
	gs := make(map[uint64]G)
	futile := make(map[*Event]bool)
	for _, ev := range events {
		switch ev.Type {
		case EvGoUnblock:
			g := gs[ev.Args[0]]
			g.wakeup = []*Event{ev}
			gs[ev.Args[0]] = g
		case EvGoStart, EvGoPreempt, EvFutileWakeup:
			g := gs[ev.G]
			g.wakeup = append(g.wakeup, ev)
			if ev.Type == EvFutileWakeup {
				g.futile = true
			}
			gs[ev.G] = g
		case EvGoBlock, EvGoBlockSend, EvGoBlockRecv, EvGoBlockSelect, EvGoBlockSync, EvGoBlockCond:
			g := gs[ev.G]
			if g.futile {
				futile[ev] = true
				for _, ev1 := range g.wakeup {
					futile[ev1] = true
				}
			}
			delete(gs, ev.G)
		}
	}

	// 第二阶段：移除无效的唤醒序列。
	newEvents := events[:0] // 覆盖原始切片
	for _, ev := range events {
		if !futile[ev] {
			newEvents = append(newEvents, ev)
		}
	}
	return newEvents
}

// 当跟踪包含不符合实际事件顺序的
// 时间戳时，通过解析返回ErrTimeOrder。
var ErrTimeOrder = fmt.Errorf("time stamps out of order")

// 后处理跟踪执行事件间验证和信息恢复。
// 结果跟踪保证一致
// （例如，一个P不同时运行两个G，或者一个G确实在取消阻止事件之前被阻止）。
func postProcessTrace(ver int, events []*Event) error {
	const (
		gDead = iota
		gRunnable
		gRunning
		gWaiting
	)
	type gdesc struct {
		state        int
		ev           *Event
		evStart      *Event
		evCreate     *Event
		evMarkAssist *Event
	}
	type pdesc struct {
		running bool
		g       uint64
		evSTW   *Event
		evSweep *Event
	}

	gs := make(map[uint64]gdesc)
	ps := make(map[int]pdesc)
	tasks := make(map[uint64]*Event)           // 任务id到任务创建事件
	activeRegions := make(map[uint64][]*Event) // goroutine id到区域堆栈
	gs[0] = gdesc{state: gRunning}
	var evGC, evSTW *Event

	checkRunning := func(p pdesc, g gdesc, ev *Event, allowG0 bool) error {
		name := EventDescriptions[ev.Type].Name
		if g.state != gRunning {
			return fmt.Errorf("g %v is not running while %v (offset %v, time %v)", ev.G, name, ev.Off, ev.Ts)
		}
		if p.g != ev.G {
			return fmt.Errorf("p %v is not running g %v while %v (offset %v, time %v)", ev.P, ev.G, name, ev.Off, ev.Ts)
		}
		if !allowG0 && ev.G == 0 {
			return fmt.Errorf("g 0 did %v (offset %v, time %v)", EventDescriptions[ev.Type].Name, ev.Off, ev.Ts)
		}
		return nil
	}

	for _, ev := range events {
		g := gs[ev.G]
		p := ps[ev.P]

		switch ev.Type {
		case EvProcStart:
			if p.running {
				return fmt.Errorf("p %v is running before start (offset %v, time %v)", ev.P, ev.Off, ev.Ts)
			}
			p.running = true
		case EvProcStop:
			if !p.running {
				return fmt.Errorf("p %v is not running before stop (offset %v, time %v)", ev.P, ev.Off, ev.Ts)
			}
			if p.g != 0 {
				return fmt.Errorf("p %v is running a goroutine %v during stop (offset %v, time %v)", ev.P, p.g, ev.Off, ev.Ts)
			}
			p.running = false
		case EvGCStart:
			if evGC != nil {
				return fmt.Errorf("previous GC is not ended before a new one (offset %v, time %v)", ev.Off, ev.Ts)
			}
			evGC = ev
			// 将其归因于全局GC状态。
			ev.P = GCP
		case EvGCDone:
			if evGC == nil {
				return fmt.Errorf("bogus GC end (offset %v, time %v)", ev.Off, ev.Ts)
			}
			evGC.Link = ev
			evGC = nil
		case EvGCSTWStart:
			evp := &evSTW
			if ver < 1010 {
				// 在1.10之前，EvGCSTWStart是per-P。
				evp = &p.evSTW
			}
			if *evp != nil {
				return fmt.Errorf("previous STW is not ended before a new one (offset %v, time %v)", ev.Off, ev.Ts)
			}
			*evp = ev
		case EvGCSTWDone:
			evp := &evSTW
			if ver < 1010 {
				// 在1.10之前，EvGCSTWDone是per-P。
				evp = &p.evSTW
			}
			if *evp == nil {
				return fmt.Errorf("bogus STW end (offset %v, time %v)", ev.Off, ev.Ts)
			}
			(*evp).Link = ev
			*evp = nil
		case EvGCSweepStart:
			if p.evSweep != nil {
				return fmt.Errorf("previous sweeping is not ended before a new one (offset %v, time %v)", ev.Off, ev.Ts)
			}
			p.evSweep = ev
		case EvGCMarkAssistStart:
			if g.evMarkAssist != nil {
				return fmt.Errorf("previous mark assist is not ended before a new one (offset %v, time %v)", ev.Off, ev.Ts)
			}
			g.evMarkAssist = ev
		case EvGCMarkAssistDone:
			// 与大多数事件不同，当
			// goroutine开始跟踪时，标记辅助可以进行，因此我们不能在这里报告错误。
			if g.evMarkAssist != nil {
				g.evMarkAssist.Link = ev
				g.evMarkAssist = nil
			}
		case EvGCSweepDone:
			if p.evSweep == nil {
				return fmt.Errorf("bogus sweeping end (offset %v, time %v)", ev.Off, ev.Ts)
			}
			p.evSweep.Link = ev
			p.evSweep = nil
		case EvGoWaiting:
			if g.state != gRunnable {
				return fmt.Errorf("g %v is not runnable before EvGoWaiting (offset %v, time %v)", ev.G, ev.Off, ev.Ts)
			}
			g.state = gWaiting
			g.ev = ev
		case EvGoInSyscall:
			if g.state != gRunnable {
				return fmt.Errorf("g %v is not runnable before EvGoInSyscall (offset %v, time %v)", ev.G, ev.Off, ev.Ts)
			}
			g.state = gWaiting
			g.ev = ev
		case EvGoCreate:
			if err := checkRunning(p, g, ev, true); err != nil {
				return err
			}
			if _, ok := gs[ev.Args[0]]; ok {
				return fmt.Errorf("g %v already exists (offset %v, time %v)", ev.Args[0], ev.Off, ev.Ts)
			}
			gs[ev.Args[0]] = gdesc{state: gRunnable, ev: ev, evCreate: ev}
		case EvGoStart, EvGoStartLabel:
			if g.state != gRunnable {
				return fmt.Errorf("g %v is not runnable before start (offset %v, time %v)", ev.G, ev.Off, ev.Ts)
			}
			if p.g != 0 {
				return fmt.Errorf("p %v is already running g %v while start g %v (offset %v, time %v)", ev.P, p.g, ev.G, ev.Off, ev.Ts)
			}
			g.state = gRunning
			g.evStart = ev
			p.g = ev.G
			if g.evCreate != nil {
				if ver < 1007 {
					// /+1，因为Symboler希望返回pc。
					ev.Stk = []*Frame{{PC: g.evCreate.Args[1] + 1}}
				} else {
					ev.StkID = g.evCreate.Args[1]
				}
				g.evCreate = nil
			}

			if g.ev != nil {
				g.ev.Link = ev
				g.ev = nil
			}
		case EvGoEnd, EvGoStop:
			if err := checkRunning(p, g, ev, false); err != nil {
				return err
			}
			g.evStart.Link = ev
			g.evStart = nil
			g.state = gDead
			p.g = 0

			if ev.Type == EvGoEnd { // 刷新所有活动区域
				regions := activeRegions[ev.G]
				for _, s := range regions {
					s.Link = ev
				}
				delete(activeRegions, ev.G)
			}

		case EvGoSched, EvGoPreempt:
			if err := checkRunning(p, g, ev, false); err != nil {
				return err
			}
			g.state = gRunnable
			g.evStart.Link = ev
			g.evStart = nil
			p.g = 0
			g.ev = ev
		case EvGoUnblock:
			if g.state != gRunning {
				return fmt.Errorf("g %v is not running while unpark (offset %v, time %v)", ev.G, ev.Off, ev.Ts)
			}
			if ev.P != TimerP && p.g != ev.G {
				return fmt.Errorf("p %v is not running g %v while unpark (offset %v, time %v)", ev.P, ev.G, ev.Off, ev.Ts)
			}
			g1 := gs[ev.Args[0]]
			if g1.state != gWaiting {
				return fmt.Errorf("g %v is not waiting before unpark (offset %v, time %v)", ev.Args[0], ev.Off, ev.Ts)
			}
			if g1.ev != nil && g1.ev.Type == EvGoBlockNet && ev.P != TimerP {
				ev.P = NetpollP
			}
			if g1.ev != nil {
				g1.ev.Link = ev
			}
			g1.state = gRunnable
			g1.ev = ev
			gs[ev.Args[0]] = g1
		case EvGoSysCall:
			if err := checkRunning(p, g, ev, false); err != nil {
				return err
			}
			g.ev = ev
		case EvGoSysBlock:
			if err := checkRunning(p, g, ev, false); err != nil {
				return err
			}
			g.state = gWaiting
			g.evStart.Link = ev
			g.evStart = nil
			p.g = 0
		case EvGoSysExit:
			if g.state != gWaiting {
				return fmt.Errorf("g %v is not waiting during syscall exit (offset %v, time %v)", ev.G, ev.Off, ev.Ts)
			}
			if g.ev != nil && g.ev.Type == EvGoSysCall {
				g.ev.Link = ev
			}
			g.state = gRunnable
			g.ev = ev
		case EvGoSleep, EvGoBlock, EvGoBlockSend, EvGoBlockRecv,
			EvGoBlockSelect, EvGoBlockSync, EvGoBlockCond, EvGoBlockNet, EvGoBlockGC:
			if err := checkRunning(p, g, ev, false); err != nil {
				return err
			}
			g.state = gWaiting
			g.ev = ev
			g.evStart.Link = ev
			g.evStart = nil
			p.g = 0
		case EvUserTaskCreate:
			taskid := ev.Args[0]
			if prevEv, ok := tasks[taskid]; ok {
				return fmt.Errorf("task id conflicts (id:%d), %q vs %q", taskid, ev, prevEv)
			}
			tasks[ev.Args[0]] = ev
		case EvUserTaskEnd:
			taskid := ev.Args[0]
			if taskCreateEv, ok := tasks[taskid]; ok {
				taskCreateEv.Link = ev
				delete(tasks, taskid)
			}
		case EvUserRegion:
			mode := ev.Args[1]
			regions := activeRegions[ev.G]
			if mode == 0 { // 区域启动
				activeRegions[ev.G] = append(regions, ev) // 推送
			} else if mode == 1 { // 区域结束
				n := len(regions)
				if n > 0 { // 匹配的区域启动事件在跟踪中。
					s := regions[n-1]
					if s.Args[0] != ev.Args[0] || s.SArgs[0] != ev.SArgs[0] { // 任务id、区域名称不匹配
						return fmt.Errorf("misuse of region in goroutine %d: span end %q when the inner-most active span start event is %q", ev.G, ev, s)
					}
					// 将区域开始事件链接到范围结束事件
					s.Link = ev

					if n > 1 {
						activeRegions[ev.G] = regions[:n-1]
					} else {
						delete(activeRegions, ev.G)
					}
				}
			} else {
				return fmt.Errorf("invalid user region mode: %q", ev)
			}
		}

		gs[ev.G] = g
		ps[ev.P] = p
	}

	// TODO（dvyukov）：还原EvGoStart事件的堆栈。
	// TODO（dvyukov）：测试所有EvGoStart事件是否具有非nil链接。

	return nil
}

// symbol将func/file/line信息附加到堆栈跟踪。
func symbolize(events []*Event, bin string) error {
	// 首先，收集并删除所有电脑的重复数据。
	pcs := make(map[uint64]*Frame)
	for _, ev := range events {
		for _, f := range ev.Stk {
			pcs[f.PC] = nil
		}
	}

	// 开始添加2行。
	cmd := exec.Command(goCmd(), "tool", "addr2line", bin)
	in, err := cmd.StdinPipe()
	if err != nil {
		return fmt.Errorf("failed to pipe addr2line stdin: %v", err)
	}
	cmd.Stderr = os.Stderr
	out, err := cmd.StdoutPipe()
	if err != nil {
		return fmt.Errorf("failed to pipe addr2line stdout: %v", err)
	}
	err = cmd.Start()
	if err != nil {
		return fmt.Errorf("failed to start addr2line: %v", err)
	}
	outb := bufio.NewReader(out)

	// 将所有PC写入ADDR2行。
	// 需要将PC复制到数组，因为映射迭代顺序是不确定的。
	var pcArray []uint64
	for pc := range pcs {
		pcArray = append(pcArray, pc)
		_, err := fmt.Fprintf(in, "0x%x\n", pc-1)
		if err != nil {
			return fmt.Errorf("failed to write to addr2line: %v", err)
		}
	}
	in.Close()

	// 阅读答案。
	for _, pc := range pcArray {
		fn, err := outb.ReadString('\n')
		if err != nil {
			return fmt.Errorf("failed to read from addr2line: %v", err)
		}
		file, err := outb.ReadString('\n')
		if err != nil {
			return fmt.Errorf("failed to read from addr2line: %v", err)
		}
		f := &Frame{PC: pc}
		f.Fn = fn[:len(fn)-1]
		f.File = file[:len(file)-1]
		if colon := strings.LastIndex(f.File, ":"); colon != -1 {
			ln, err := strconv.Atoi(f.File[colon+1:])
			if err == nil {
				f.File = f.File[:colon]
				f.Line = ln
			}
		}
		pcs[pc] = f
	}
	cmd.Wait()

	// 替换事件数组中的帧。
	for _, ev := range events {
		for i, f := range ev.Stk {
			ev.Stk[i] = pcs[f.PC]
		}
	}

	return nil
}

// readVal从r读取无符号的base-128值。
func readVal(r io.Reader, off0 int) (v uint64, off int, err error) {
	off = off0
	for i := 0; i < 10; i++ {
		var buf [1]byte
		var n int
		n, err = r.Read(buf[:])
		if err != nil || n != 1 {
			return 0, 0, fmt.Errorf("failed to read trace at offset %d: read %v, error %v", off0, n, err)
		}
		off++
		v |= uint64(buf[0]&0x7f) << (uint(i) * 7)
		if buf[0]&0x80 == 0 {
			return
		}
	}
	return 0, 0, fmt.Errorf("bad value at offset 0x%x", off0)
}

// 打印将事件转储到标准输出。用于调试。
func Print(events []*Event) {
	for _, ev := range events {
		PrintEvent(ev)
	}
}

// PrintEvent将事件转储到标准输出。用于调试。
func PrintEvent(ev *Event) {
	fmt.Printf("%s\n", ev)
}

func (ev *Event) String() string {
	desc := EventDescriptions[ev.Type]
	w := new(bytes.Buffer)
	fmt.Fprintf(w, "%v %v p=%v g=%v off=%v", ev.Ts, desc.Name, ev.P, ev.G, ev.Off)
	for i, a := range desc.Args {
		fmt.Fprintf(w, " %v=%v", a, ev.Args[i])
	}
	for i, a := range desc.SArgs {
		fmt.Fprintf(w, " %v=%v", a, ev.SArgs[i])
	}
	return w.String()
}

// argNum返回事件的arg总数，说明时间戳，
// 序列号和跟踪格式版本之间的差异。
func argNum(raw rawEvent, ver int) int {
	desc := EventDescriptions[raw.typ]
	if raw.typ == EvStack {
		return len(raw.args)
	}
	narg := len(desc.Args)
	if desc.Stack {
		narg++
	}
	switch raw.typ {
	case EvBatch, EvFrequency, EvTimerGoroutine:
		if ver < 1007 {
			narg++ // 在1.7 
		}
		return narg
	}
	narg++ // 时间戳
	if ver < 1007 {
		narg++ // 序列
	}
	switch raw.typ {
	case EvGCSweepDone:
		if ver < 1009 {
			narg -= 2 // 1.9添加了两个参数
		}
	case EvGCStart, EvGoStart, EvGoUnblock:
		if ver < 1007 {
			narg-- // 1.7添加了一个额外的seq arg 
		}
	case EvGCSTWStart:
		if ver < 1010 {
			narg-- // 1.10添加了一个参数
		}
	}
	return narg
}

// BreakTimestampsForTesting导致解析器随机更改时间戳（用于测试损坏的CPK）。
var BreakTimestampsForTesting bool

// 跟踪中的事件类型。
// 从src/runtime/trace.go逐字复制，删除“trace”前缀。
const (
	EvNone              = 0  // 未使用的
	EvBatch             = 1  // 每P批事件的开始[pid，时间戳]
	EvFrequency         = 2  // 包含跟踪计时器频率[频率（每秒节拍数）]
	EvStack             = 3  // 堆栈[堆栈id，PC数量，{PC数组，函数字符串id，文件字符串id，行}]
	EvGomaxprocs        = 4  // GOMAXPROCS的当前值[timestamp，GOMAXPROCS，stack id]
	EvProcStart         = 5  // P的开始[timestamp，线程id]
	EvProcStop          = 6  // P的停止[timestamp]
	EvGCStart           = 7  // GC start[timestamp，seq，stack id]
	EvGCDone            = 8  // GC done[timestamp]
	EvGCSTWStart        = 9  // GC mark termination start[timestamp，kind]
	EvGCSTWDone         = 10 // GC标记终止完成【时间戳】
	EvGCSweepStart      = 11 // GC扫描开始【时间戳，堆栈id】
	EvGCSweepDone       = 12 // GC扫描完成【时间戳，扫描，回收】
	EvGoCreate          = 13 // goroutine创建【时间戳，新goroutine id，新堆栈id，堆栈id】
	EvGoStart           = 14 // goroutine开始运行[timestamp，goroutine id，seq]
	EvGoEnd             = 15 // goroutine ends[timestamp]
	EvGoStop            = 16 // goroutine stops（如select{}）[timestamp，stack]
	EvGoSched           = 17 // goroutine调用Gosched[timestamp，stack]
	EvGoPreempt         = 18 // goroutine被抢占[timestamp，stack]
	EvGoSleep           = 19 // goroutine调用Sleep[timestamp，stack]
	EvGoBlock           = 20 // goroutine blocks[timestamp，stack]
	EvGoUnblock         = 21 // goroutine被解锁[timestamp，goroutine id，seq，stack]
	EvGoBlockSend       = 22 // goroutine blocks on chan send[timestamp，stack]
	EvGoBlockRecv       = 23 // goroutine blocks on chan recv[timestamp，stack]
	EvGoBlockSelect     = 24 // GOROUTE blocks on select[timestamp，stack]
	EvGoBlockSync       = 25 // GOROUTE blocks on Mutex/RWMutex[timestamp，stack]
	EvGoBlockCond       = 26 // goroutine blocks on Cond[timestamp，stack]
	EvGoBlockNet        = 27 // goroutine blocks on network[timestamp，stack]
	EvGoSysCall         = 28 // syscall enter[timestamp，stack]
	EvGoSysExit         = 29 // syscall exit[timestamp，goroutine id，seq，real timestamp]
	EvGoSysBlock        = 30 // syscall blocks[timestamp]
	EvGoWaiting         = 31 // 表示在跟踪开始[timestamp，goroutine id]时goroutine被阻塞
	EvGoInSyscall       = 32 // 表示在跟踪开始[timestamp，goroutine id]
	EvHeapAlloc         = 33 // gcController.heapLive change[timestamp，heap live bytes]
	EvHeapGoal          = 34 // gcController.heapGoal change时goal处于系统调用中[timestamp，heap goal bytes]
	EvTimerGoroutine    = 35 // 表示计时器goroutine[timer goroutine id]
	EvFutileWakeup      = 36 // 表示此goroutine的上一次唤醒无效[timestamp]
	EvString            = 37 // 字符串字典项[id，length，string]
	EvGoStartLocal      = 38 // goroutine开始在与上一个事件相同的P上运行[timestamp，goroutine id]
	EvGoUnblockLocal    = 39 // goroutine在与上一个事件相同的P上解除阻止[timestamp，goroutine id，stack]
	EvGoSysExitLocal    = 40 // 系统调用在与上一个事件相同的P上退出[timestamp，goroutine id，real timestamp]
	EvGoStartLabel      = 41 // goroutine开始运行时使用标签[timestamp，goroutine id，seq，label string id]
	EvGoBlockGC         = 42 // GC-assist上的goroutine块[timestamp，stack]
	EvGCMarkAssistStart = 43 // GC-mark-assist-start[timestamp，stack]
	EvGCMarkAssistDone  = 44 // GC mark assist-done[timestamp]
	EvUserTaskCreate    = 45 // trace.NewContext[timestamp，internal task-id，internal parent-id，stack，name-string]
	EvUserTaskEnd       = 46 // 任务结束[时间戳，内部任务id，堆栈]
	EvUserRegion        = 47 // trace.WithRegion[时间戳，内部任务id，模式（0:start，1:end），堆栈，名称字符串]
	EvUserLog           = 48 // trace.Log[时间戳，内部id，键字符串id，堆栈，值字符串]
	EvCount             = 49
)

var EventDescriptions = [EvCount]struct {
	Name       string
	minVersion int
	Stack      bool
	Args       []string
	SArgs      []string // 字符串参数
}{
	EvNone:              {"None", 1005, false, []string{}, nil},
	EvBatch:             {"Batch", 1005, false, []string{"p", "ticks"}, nil}, // 在1.5格式中是{“p”、“seq”、“ticks”}
	EvStack:             {"Stack", 1005, false, []string{"id", "siz"}, nil},
	EvGomaxprocs:        {"Gomaxprocs", 1005, true, []string{"procs"}, nil},
	EvProcStart:         {"ProcStart", 1005, false, []string{"thread"}, nil},
	EvProcStop:          {"ProcStop", 1005, false, []string{}, nil},
	EvGCDone:            {"GCDone", 1005, false, []string{}, nil},
	EvGCSTWDone:         {"GCSTWDone", 1005, false, []string{}, nil},
	EvGCSweepStart:      {"GCSweepStart", 1005, true, []string{}, nil},
	EvGoCreate:          {"GoCreate", 1005, true, []string{"g", "stack"}, nil},
	EvGoStart:           {"GoStart", 1005, false, []string{"g", "seq"}, nil}, // 1.5格式为{“g”}
	EvGoEnd:             {"GoEnd", 1005, false, []string{}, nil},
	EvGoStop:            {"GoStop", 1005, true, []string{}, nil},
	EvGoSched:           {"GoSched", 1005, true, []string{}, nil},
	EvGoPreempt:         {"GoPreempt", 1005, true, []string{}, nil},
	EvGoSleep:           {"GoSleep", 1005, true, []string{}, nil},
	EvGoBlock:           {"GoBlock", 1005, true, []string{}, nil},
	EvGoUnblock:         {"GoUnblock", 1005, true, []string{"g", "seq"}, nil}, // 1.5格式为{“g”}
	EvGoBlockSend:       {"GoBlockSend", 1005, true, []string{}, nil},
	EvGoBlockRecv:       {"GoBlockRecv", 1005, true, []string{}, nil},
	EvGoBlockSelect:     {"GoBlockSelect", 1005, true, []string{}, nil},
	EvGoBlockSync:       {"GoBlockSync", 1005, true, []string{}, nil},
	EvGoBlockCond:       {"GoBlockCond", 1005, true, []string{}, nil},
	EvGoBlockNet:        {"GoBlockNet", 1005, true, []string{}, nil},
	EvGoSysCall:         {"GoSysCall", 1005, true, []string{}, nil},
	EvGoSysExit:         {"GoSysExit", 1005, false, []string{"g", "seq", "ts"}, nil},
	EvGoSysBlock:        {"GoSysBlock", 1005, false, []string{}, nil},
	EvGoWaiting:         {"GoWaiting", 1005, false, []string{"g"}, nil},
	EvGoInSyscall:       {"GoInSyscall", 1005, false, []string{"g"}, nil},
	EvHeapAlloc:         {"HeapAlloc", 1005, false, []string{"mem"}, nil},
	EvHeapGoal:          {"HeapGoal", 1005, false, []string{"mem"}, nil},
	EvTimerGoroutine:    {"TimerGoroutine", 1005, false, []string{"g"}, nil}, // 1.5格式为{“g”，“未使用”}
	EvFutileWakeup:      {"FutileWakeup", 1005, false, []string{}, nil},
	EvString:            {"String", 1007, false, []string{}, nil},
	EvGoStartLocal:      {"GoStartLocal", 1007, false, []string{"g"}, nil},
	EvGoUnblockLocal:    {"GoUnblockLocal", 1007, true, []string{"g"}, nil},
	EvGoSysExitLocal:    {"GoSysExitLocal", 1007, false, []string{"g", "ts"}, nil},
	EvGoStartLabel:      {"GoStartLabel", 1008, false, []string{"g", "seq", "labelid"}, []string{"label"}},
	EvGoBlockGC:         {"GoBlockGC", 1008, true, []string{}, nil},
	EvGCMarkAssistStart: {"GCMarkAssistStart", 1009, true, []string{}, nil},
	EvGCMarkAssistDone:  {"GCMarkAssistDone", 1009, false, []string{}, nil},
	EvUserTaskCreate:    {"UserTaskCreate", 1011, true, []string{"taskid", "pid", "typeid"}, []string{"name"}},
	EvUserTaskEnd:       {"UserTaskEnd", 1011, true, []string{"taskid"}, nil},
	EvUserRegion:        {"UserRegion", 1011, true, []string{"taskid", "mode", "typeid"}, []string{"name"}},
	EvUserLog:           {"UserLog", 1011, true, []string{"id", "keyid"}, []string{"category", "message"}},
}
